<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Drum Kit</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <div class="key" data-key="KeyA">
            <audio src="sounds/clap.wav"></audio>
            <h2>A</h2>
            <p>CLAP</p>
        </div>
        <div class="key" data-key="KeyS">
            <audio src="sounds/hihat.wav"></audio>
            <h2>S</h2>
            <p>HIHAT</p>
        </div>
        <div class="key" data-key="KeyD">
            <audio src="sounds/kick.wav"></audio>
            <h2>D</h2>
            <p>KICK</p>
        </div>
        <div class="key" data-key="KeyF">
            <audio src="sounds/openhat.wav"></audio>
            <h2>F</h2>
            <p>OPENHAT</p>
        </div>
        <div class="key" data-key="KeyG">
            <audio src="sounds/boom.wav"></audio>
            <h2>G</h2>
            <p>BOOM</p>
        </div>
        <div class="key" data-key="KeyH">
            <audio src="sounds/ride.wav"></audio>
            <h2>H</h2>
            <p>RIDE</p>
        </div>
        <div class="key" data-key="KeyJ">
            <audio src="sounds/snare.wav"></audio>
            <h2>J</h2>
            <p>SNARE</p>
        </div>
        <div class="key" data-key="KeyK">
            <audio src="sounds/tom.wav"></audio>
            <h2>K</h2>
            <p>TOM</p>
        </div>
        <div class="key" data-key="KeyL">
            <audio src="sounds/tink.wav"></audio>
            <h2>L</h2>
            <p>TINK</p>
        </div>
    </div>
    <script>
        
        //1.监听键盘点击事件
        //2.获得code
        //3.通过keycode查找 对应的div.key
        //4.通过div.key间接查询找到下面的 audio
        //5.调用audio.play()方法，添加playing

        //1.监听键盘点击事件
        window.onkeypress = function(e){
            //2.获得code
            let code = e.code
            //3.通过keycode查找 对应的div.key
            let activeKeyEle = document.querySelector(`div.key[data-key=${code}]`)
            //4.给元素添加一个class:playing，过200ms以后就删除这个class:playing
            flashClass(activeKeyEle,'playing',200)
            //5.找到这个div.key下面的audio
            let activeAudio = activeKeyEle.querySelector('audio')
            //6.播放这个音频
            activeAudio.play()
        }
        //封装一个函数，给元素el添加一个className,持续事件为during,当时间超过during就把元素el的className取消
        function flashClass(el,className,during){
            //给元素添加一个className
            el.classList.add(className)
            //设置一个演示器，过一段时间(during，单位毫秒ms)把元素的className删除
            setTimeout(function(){
                el.classList.remove(className)
            },during)
        }
        
    </script>

</body>

</html>